import Modal from '../ui/Modal';
import Table from '../ui/table';
import Dom from '../utils/Dom';
import Http from '../utils/Http';
import Config from '../config';
import Utils from '../utils/index';
import MasterDataModal from './MasterDataModal';
import Select from '../ui/Select';

class GanttModal {
   constructor(Gantt) {
      this.Gantt = Gantt;
      this.pdiModal = null;
      this.pdiModalCallback = null;

      this.castModal = null;
      this.castModalCallback = null;

      this.heatHotFlagModal = null;
      this.heatHotFlagModalCallback = null;
   }



   // PDI modal

	/**
	 * 生成 PDI modal 内容
	 * @param {DOM} body PDI modal body
	 */
   generatePdiModalContent(body) {
      // if(!this.pdiModal.leftContainer) {
      body.className += ' pdi-modal';
      this.pLeftContainer = Dom.append(body, 'div', 'pid-left');
      this.pRightContainer = Dom.append(body, 'div', 'pid-right');

      Dom.append(this.pLeftContainer, 'p', null, '计划炉次号');
      this.heatSid = Dom.append(this.pLeftContainer, 'input');
      this.heatSid.type = 'text';
      this.heatSid.setAttribute('readonly', true);

      Dom.append(this.pLeftContainer, 'p', null, 'GE 编号');
      this.geNo = Dom.append(this.pLeftContainer, 'ul', 'pid-input-list');
      this.geNo.style.height = '118px';

      this.sgrs = Dom.append(this.pLeftContainer, 'label', null, '<input type="checkbox"> SGRS 工艺');
      this.sgrs.style.cursor = 'pointer';
      this.sgrs.style.display = 'inline-block';
      this.sgrs.style['margin-top'] = '5px';

      Dom.addEvent(this.geNo, 'click', e => {
         if (e.target.tagName === 'LI' && e.target.className.indexOf('active') === -1) {
            this.geNo.childNodes.forEach(li => {
               li.className = li.className.replace(' active', '');
            });

            e.target.className += ' active';
         }
      });

      Dom.append(this.pRightContainer, 'p', null, 'BOF 二级计划号');
      this.matches = Dom.append(this.pRightContainer, 'ul', 'pid-input-list');

      Dom.addEvent(this.matches, 'click', e => {
         if (e.target.tagName === 'LI' && e.target.className.indexOf('active') === -1) {
            this.matches.childNodes.forEach(li => {
               li.className = li.className.replace(' active', '');
            });
            e.target.className += ' active';
         }
      });
   }

	/**
	 * 根据数据更新 PDI modal 内容
	 * @param {Object} data
	 */
   updatePdiModal(data) {
      this.heatSid.value = data.sid;

      let geNoStr = '',
         selected = false,
         className = null,
         matcheStr = '';


      data.geNo.forEach((ge, index) => {
         if (!selected && ge.startsWith(data.routeIdSubfix)) {
            selected = true;
            className = 'class=" active"';
         } else {
            className = '';
         }
         geNoStr += '<li data-index="' + index + '" ' + className + '>' + ge + '</li>';
      });
      this.geNo.innerHTML = geNoStr;

      this.sgrs.childNodes[0].checked = false;
      // this.sgrs.checked = false;

      selected = false;
      data.matches.forEach((m, index) => {
         className = '';
         if (m[1] === 'U') {
            className = 'disabled';
         } else if (!selected) {
            className = ' active';
            selected = true;
         }
         if (className) {
            className = 'class="' + className + '"';
         }
         matcheStr += '<li data-index="' + index + '"' + className + '>' + m[0] + '</li>';
      });

      this.matches.innerHTML = matcheStr
   }

	/**
	 * 获取 PDI modal 数据
	 * @param {Object} data
	 */
   getPdiData(data) {
      let postData = {
         sid: data.sid,
         matchSid: null,
         geNo: null,
         sgrp: null
      },
         i = 0,
         total = this.geNo.childNodes.length;
      for (; i < total; i++) {
         if (this.geNo.childNodes[i].className.indexOf(' active') !== -1) {
            postData.geNo = this.geNo.childNodes[i].innerText;
            break;
         }
      }

      i = 0;
      total = this.matches.childNodes.length;
      for (; i < total; i++) {
         if (this.matches.childNodes[i].className.indexOf(' active') !== -1) {
            let matchIndex = parseInt(this.matches.childNodes[i].getAttribute('data-index'));
            postData.matchSid = data.matches[matchIndex][2];
            break;
         }
      }

      postData.sgrp = this.sgrs.childNodes[0].checked ? 'Y' : 'N';

      console.log(postData);
      return postData;
   }

	/**
	 * 显示 PDI 弹窗
	 * @param {Object} data
	 * @param {function} callback // 确定按钮点击回调函数
	 */
   showPdiModal(data, callback) {
      this.pdiModalCallback = callback;
      if (!this.pdiModal) {
         this.pdiModal = new Modal('下 PDI', body => {
            this.generatePdiModalContent(body);
         }, isOk => {
            if (isOk) {
               this.Gantt.showLoading();
               Http.get(Config.api.downPdiMatch, this.getPdiData(data), result => {
                  this.pdiModal.show(true);
                  this.pdiModalCallback(result[0]);
               });
            }
         })
      } else {
         this.pdiModal.show();
      }
      this.updatePdiModal(data);
   }

	/**
	 * Cast Modal
	 */

   showCastModal(data, callback, facilities) {

      if (data.isDefaultRoute && !data.isFirst) {
         Http.get(Config.api.scheduleDefaultCast, {
            sid: data.sid
         }, result => {
            callback(result);
         })
         return false;
      }
      this.castModalData = data;
      this.castModalCallback = callback;
      if (!this.castModal) {
         this.castModal = new Modal('调度炉次', body => {
            this.generateCastModalContent(body, facilities)
         }, isOk => {
            if (isOk) {
               let postData = this.getCastData(this.castModalData),
                  url = null;

               if (this.castModalData.isDefaultRoute) {
                  url = this.castModalData.isFirst ? Config.api.scheduleDefaultCastFirst : Config.api.scheduleDefaultCast
               } else {
                  url = this.castModalData.isFirst ? Config.api.scheduleInverseFirst : Config.api.scheduleInverse;
               }
               this.Gantt.showLoading();
               Http.get(url, postData, result => {
                  this.castModal.show(true);
                  this.castModalCallback(result);
               });
            }
         });
      } else {
         this.castModal.show();
      }

      this.updateCastModal(data);
   }


   generateCastModalContent(body, facilities) {
      body.className += ' cast-modal';

      this.castFacilityP = Dom.append(body, 'p', null, '<span class="label">设备</span>');
      let selectOptions = '';
      facilities.forEach(f => {
         if (f.facilityType === 'B') {
            selectOptions += '<option value="' + f.facilityNo + '">' + f.facilityDesc + '</option>';
         }
      })
      this.castFacility = Dom.append(this.castFacilityP, 'select', null, selectOptions);

      this.castPlanP = Dom.append(body, 'p', null, '<span class="label">计划开始时间</span>');
      this.castPlanDate = Dom.append(this.castPlanP, 'input');
      this.castPlanDate.type = 'datetime-local';
      this.castPlanDate.step = 1;

      this.castPlanCcmP = Dom.append(body, 'p', null, '<span class="label">浇铸时长(min)</span>');
      this.castPlanCcmDate = Dom.append(this.castPlanCcmP, 'input');


      this.castRouteP = Dom.append(body, 'p', null, '工艺路径');
      this.castRoute = Dom.append(body, 'ul', 'pid-input-list');
      this.castRoute.style.height = '180px';

      Dom.addEvent(this.castRoute, 'click', e => {
         if (e.target.tagName === 'LI' && e.target.className.indexOf('active') === -1) {
            this.castRoute.childNodes.forEach(li => {
               li.className = li.className.replace(' active', '');
            });
            e.target.className += ' active';
         }
      })
   }

   updateCastModal(data) {
      if (data.isFirst) {
         this.castFacilityP.style.display = 'block';
         this.castPlanP.style.display = 'block';
         this.castPlanCcmP.style.display = 'block';
         this.castPlanDate.value = Utils.dateFormat(null, '-', true).replace(' ', 'T');
            //指定设备号
         this.castFacility.value = data.facilityCcm;
         this.castPlanCcmDate.value = '';

      } else {
         this.castFacilityP.style.display = 'none';
         this.castPlanP.style.display = 'none';
         this.castPlanCcmP.style.display = 'none';
      }

      if (data.isDefaultRoute) {
         this.castRoute.style.display = 'none';
         this.castRouteP.style.display = 'none';
         return false;
      }

      let routeStr = '';
      data.routes.forEach((r, i) => {
         routeStr += '<li ' + (i === 0 ? 'class=" active"' : '') + '>' + r.split('_').join(' -> ') + '</li>';
      });
      this.castRoute.innerHTML = routeStr;
      this.castRoute.style.display = 'block';
      this.castRouteP.style.display = 'block';
   }

   getCastData(data) {
      let postData = {
         sid: data.sid,
         route: null
      },
         i = 0,
         total = this.castRoute.childNodes.length;
      for (; i < total; i++) {
         if (this.castRoute.childNodes[i].className.indexOf(' active') !== -1) {
            postData.route = this.castRoute.childNodes[i].innerText.split(' -> ');
            break;
         }
      }

      if (data.isFirst) {
         postData.facilityNo = this.castFacility.value;
         postData.firstTime = Utils.dateFill(this.castPlanDate.value);
         postData.ccmDate = this.castPlanCcmDate.value;
      }

      if (!data.isDefaultRoute) {
         postData.route = postData.route.join('_');
      }
      return postData;
   }


   showHeatHotFlagModal(data, callback) {
      this.hotFlagData = data;
      this.heatHotFlagModalCallback = callback;
      if (!this.heatHotFlagModal) {
         this.heatHotFlagModal = new Modal('设置堆冷信息', body => {
            this.generateHeatHotFlagModalContent(body)
         }, isOk => {
            if (isOk) {
               let postData = {
                  sid: this.hotFlagData.sid,
                  hotFlag: this.heatHotFlagData.value,
                  heatColdDateVal: this.heatColdDateVal.value
               },
                  url = Config.api.changeHotFlag;
               this.Gantt.showLoading();
               Http.get(url, postData, result => {
                  this.heatHotFlagModal.show(true);
                  this.heatHotFlagModalCallback(result);
               });
            }
         });
      } else {
         this.heatHotFlagModal.show();
      }
      this.heatHotFlagData.value = '1';
      this.heatColdDateVal.value = '';
   }

   generateHeatHotFlagModalContent(body) {
      body.className += ' heat-hot-flag-modal';
      this.heatHotFlag = Dom.append(body, 'p', null, '<span class="label">是否转堆冷</span>');
      let selectOptions = '<option value="1">是</option> <option value="0">否</option>';
      this.heatHotFlagData = Dom.append(this.heatHotFlag, 'select', null, selectOptions);

      this.heatColdDate = Dom.append(body, 'p', null, '<span class="label">堆冷时长(h)</span>');
      this.heatColdDateVal = Dom.append(this.heatColdDate, 'input');
   }

   showCastInfo(data) {
      // let template = `
      // 	<table>
      // 		<thead><tr><th>计划炉次号</th><th>CA 编号</th><th>炉次重量</th><th>炉次状态</th></tr></thead>
      // 		<tbody>
      // 	`;
      // data.heats.forEach(h => {
      // 	template += '<tr><td>' + h.taskCounter + '</td><td>' + h.caId + '</td><td>' + h.heatWeight + '</td><td>' + h.heatStat + '</td></tr>';
      // });

      this.showInfoModal(body => {
         Dom.append(body, 'p', null, '<p><span class="label">浇次号</span> <input value="' + data.cast.castNo + '" readonly></p>');
         new Table(body, [{
            name: '计划炉次号',
            key: 'taskCounter'
         }, {
            name: '出钢标记',
            key: 'caId'
         }, {
            name: '炉次重量',
            key: 'heatWeight'
         }, {
            name: '炉次状态',
            key: 'heatStat'
         }], data.heats)
      }, '浇次信息');
   }

   showHeatInfo(data) {
      let props = [{
         key: 'taskCounter',
         label: '计划炉次号'
      }, {
         key: 'heatId',
         label: '实际炉次号'
      }, {
         key: 'castNo',
         label: '浇次号'
      }, {
         key: 'castHtNo',
         label: '炉次顺序号'
      }, {
         key: 'caId',
         label: '外部钢种'
      }, {
         key: 'caDescr',
         label: '出钢标记'
      }, {
         key: 'heatRemark',
         label: '备注'
      }, {
         key: 'heatWeight',
         label: '炉次重量'
      }],
         html = '';

      console.log(data);

      props.forEach(p => {
         html += '<p><span class="label">' + p.label + '</span><input value="' + (data[p.key] || '') + '" readonly></p>';
      })

      this.showInfoModal(html, '炉次信息');
   }

   showSlabInfo(data) {
      let template = `<table><thead><tr><th>计划板坯号</th><th>计划炉次号</th><th>板坯宽度</th>
			<th>板坯厚度</th><th>板坯长度</th><th>板坯理重</th></tr></thead>
			`
      data.forEach(d => {
         template += '<tr><td>' + d.virtualSlabNo + '</td><td>' + d.taskCounter + '</td>' +
            '<td>' + d.slabWidth + '</td><td>' + d.slabHeight + '</td><td>' + d.slabLength + '</td><td>' + d.slabWeight + '</td></tr>';
      });
      this.showInfoModal(template + '</table>', '板坯信息', 600);
   }

   showInfoModal(content, title, width = 460) {
      if (typeof content === 'string') {
         content = '<div class="info-modal">' + content + '</div>';
      }

      if (!this.infoModal) {
         this.infoModal = new Modal(title, content, isOK => {
            this.infoModal.show(true);
         });
         this.infoModal.successBtn.style.display = 'none';
         this.infoModal.cancelBtn.innerText = '关闭';
      } else {
         this.infoModal.setContent(content);
         this.infoModal.title.innerHTML = title;
         this.infoModal.show();
      }
      this.infoModal.modal.style.width = width + 'px';
   }

   // 插入作业弹窗
   showInsertOperationModal(callback, facilities) {
      if (!this.insertOperationModal) {
         this.insertOperationModal = new Modal('插入作业', body => {
            body.className += ' operation-modal';
            let p = Dom.append(body, 'p', null, '<span class="label">设备</span>'),
               selectOptions = '';
            facilities.forEach(f => {
               selectOptions += '<option value="' + f.facilityNo + '">' + f.facilityDesc + '</option>';
            });
            this.operationFacility = Dom.append(p, 'select', null, selectOptions);

            p = Dom.append(body, 'p', null, '<span class="label">计划开始时间</span>');

            this.operationStartTime = Dom.append(p, 'input', null, null, null, {
               type: 'datetime-local',
               step: 1
            });
            this.operationStartTime.value = Utils.dateFormat(null, '-', true).replace(' ', 'T');



            p = Dom.append(body, 'p', null, '<span class="label">计划结束时间</span>');
            this.operationEndTime = Dom.append(p, 'input', null, null, null, {
               type: 'datetime-local',
               step: 1
            });
            this.operationEndTime.value = Utils.dateFormat(new Date().getTime() + Utils.timeUnit.minutes * 30, '-', true).replace(' ', 'T');
         }, isOK => {
            if (isOK) {
               let start = this.operationStartTime.value,
                  end = this.operationEndTime.value;
               if (!start || start.length < 10 || !end || end.length < 10) {
                  return false;
               }
               start = Utils.dateFill(start);
               end = Utils.dateFill(end);

               callback({
                  facilityNo: this.operationFacility.value,
                  planStartTime: start,
                  planEndTime: end
               });
            }
            this.insertOperationModal.hide();
         });
      } else {
         // 更新
         this.operationStartTime.value = Utils.dateFormat(null, '-', true).replace(' ', 'T');;
         this.operationEndTime.value = Utils.dateFormat(new Date().getTime() + Utils.timeUnit.minutes * 30, '-', true).replace(' ', 'T');;
         this.operationFacility.value = facilities[0].facilityNo;
         this.insertOperationModal.show();
      }
   }

   /**
    * 单模式下修改作业时间，京唐特有
    * @param {*} callback
    * @param {*} startTime
    * @param {*} endTime
    */
   changeHeatOperationTime(callback,startTime,endTime){
      if(!this.changeHeatOperationTimeModal){
            this.changeHeatOperationTimeModal = new Modal('修改作业时间', body => {
                  body.className += ' operation-modal';
                  let s = Dom.append(body, 'p', null, '<span class="label">新的开始时间</span>');
                  this.changeNewStartTime = Dom.append(s, 'input', null, null, null, {
                     type: 'datetime-local',
                     step: 1
                  });
                  let e = Dom.append(body, 'p', null, '<span class="label">新的结束时间</span>');
                  this.changeNewEndTime = Dom.append(e, 'input', null, null, null, {
                     type: 'datetime-local',
                     step: 1
                  });
               }, isOK => {
                  if (isOK) {
                     let start = this.changeNewStartTime.value;
                     let end = this.changeNewEndTime.value;
                     if (!start || start.length < 10||!end||end.length<10) {
                        return false;
                     }
                     callback(Utils.dateFill(start),Utils.dateFill(end));
                  }
                  this.changeHeatOperationTimeModal.show(true);
               });
      }else{
            this.changeHeatOperationTimeModal.show();
      }
      this.changeNewStartTime.value = (startTime || Utils.dateFormat(null, '-', true)).replace(' ', 'T');
      this.changeNewEndTime.value = (endTime || Utils.dateFormat(null, '-', true)).replace(' ', 'T');
   }

   //  更新操作时间弹窗
   showOperationModal(callback, value) {
      if (!this.operationModal) {
         this.operationModal = new Modal('修改时间', body => {
            body.className += ' operation-modal';
            let p = Dom.append(body, 'p', null, '<span class="label">新的开始时间</span>');
            this.operationNewStartTime = Dom.append(p, 'input', null, null, null, {
               type: 'datetime-local',
               step: 1
            });
         }, isOK => {
            if (isOK) {
               let start = this.operationNewStartTime.value;
               if (!start || start.length < 10) {
                  return false;
               }
               callback(Utils.dateFill(start));
            }
            this.operationModal.show(true);
         });
      } else {

         this.operationModal.show();
      }
      this.operationNewStartTime.value = (value || Utils.dateFormat(null, '-', true)).replace(' ', 'T');

   }

	/**
	 * 单个下拉框选择弹窗，适用于 合并浇次、炉次更换浇次、炉次信息互换
	 * @param {Array} list 数据列表
	 * @param {string} key 下拉选显示文字的 key
	 * @param {String} currentValue 当前的值，用于过滤掉当前值
	 * @param {function} callback 回调函数
	 * @param {Object} options 配置，包含 title, label
	 */
   singleSelectModal(list, key, currentValue, callback, options) {
      let select = null,
         p = null,
         optionStr = '',
         modal = new Modal(options.title, body => {
            p = Dom.append(body, 'p', null, '<span class="label">' + options.label + '</span>');
            list.forEach(l => {
               if (currentValue && currentValue === l[key]) {
                  return;
               }
               optionStr += '<option value="' + l.sid + '">' + l[key] + '</option>';
            });
            select = Dom.append(p, 'select', null, optionStr);
         }, isOk => {
            if (!isOk || callback(select.value)) {
               modal.destroy(true);
            }
         });
   }

   // 简单的单选模态框
   simpleSingleSelectModal(title, list, callback, options) {
      let select = null,
         p = null,
         optionStr = null,
         modal = new Modal(title, body => {
            p = Dom.append(body, 'p', null, '<span class="label">' + options.label + '</span>');
            list.forEach(l => {
               optionStr += '<option value="' + l + '">' + l + '</option>';
            });
            select = Dom.append(p, 'select', null, optionStr);
         }, isOk => {
            if (!isOk || callback(select.value, modal)) {
               modal.destroy(true);
            }
         });
   }

   // 时间跳转 modal
   gotoModal(currentTime, callback) {
      let timeInput,
         modal = new Modal('时间跳转', body => {
            timeInput = Dom.append(body, 'input', null, null, null, {
               type: 'datetime-local',
               step: 1
            });
            timeInput.style.width = '100%';
            timeInput.value = (currentTime || Utils.dateFormat(null, '-', true)).replace(' ', 'T');
         }, isOK => {
            if (!isOK || callback(timeInput.value.replace('T', ' '))) {
               modal.destroy(true);
            }
         }, {
               className: 'modal-small'
            });
   }

   showHeatChangeModal(currentHeat, callback) {
      if (!this.heatChaneModal) {
         this.heatChaneModal = new Modal('炉次交换', body => {
            let p = Dom.append(body, 'p', null, '<span class="label">计划炉次号：</span>');
            this.heatChangeInput = Dom.append(p, 'input');
            this.heatChangeInput.setAttribute('readonly', true);

            p = Dom.append(body, 'p', null, '<span class="label">计划炉次号：</span>');

            this.heatChangeInput2 = Dom.append(p, 'input');
            this.heatChangeInput2.setAttribute('readonly', true);
         }, isOk => {
            if (!isOk || this.heatChangeInput2.value) {
               callback(isOk);
            } else {
               return false;
            }
            this.heatChaneModal.show(true);
         }, {
               dimmer: false
            });
      }
      this.heatChangeInput.value = currentHeat;
      this.heatChangeInput2.value = null;
      this.heatChaneModal.show();
   }

   showMasterDataModal(type) {
      if (!this.masterDataModal) {
         this.masterDataModal = new MasterDataModal(type, this.Gantt);
      } else {
         this.masterDataModal.setTable(type);
      }
   }


   // 定时刷新数据更新通知弹窗
   showDataUpdatedModal(updates) {
      if (!this.dataUpdatedModal) {
         this.dataUpdatedModalContainer = null;
         this.dataUpdatedModal = new Modal('MCCR 调度信息变更', body => {
            this.dataUpdatedModalContainer = Dom.append(body, 'div', 'data-updated-container');

         }, () => {
            this.dataUpdatedModal.show(true);
         }, {
               className: 'data-updated-modal',
               dimmer: false
            });
         this.dataUpdatedModal.cancelBtn.style.display = 'none';
      }

      let html = '';
      updates.forEach(u => {
         html += '<p>' + u + '</p>';
      });
      this.dataUpdatedModalContainer.innerHTML = html;
      this.dataUpdatedModal.show();
   }

   showStaticScheduleModal(casts, facilities, callback) {
      this.staticScheduleCasts = casts;
      this.staticScheduleSelectedCasts = [];
      this.staticScheduleFacilities = facilities;
      this.staticScheduleCallback = callback;

      if (!this.staticScheduleModal) {

         this.staticScheduleModal = new Modal('静态算法调度', body => {
            body.className += ' static-schedule';

            // 计算开始时间
            let p = Dom.append(body, 'p', null, '<span>计划开始时间</span>');
            this.staticScheduleStartTime = Dom.append(p, 'input', null, null, null, {
               type: 'datetime-local',
               step: 1
            });
            Dom.append(p, 'span', null, '设备');
            // 设备
            this.staticScheduleFacilityDom = Dom.append(p, 'select');

            let wrapper = Dom.append(body, 'div', 'static-schedule-select');
            // 浇次选择
            this.staticScheduleCastsEl = new Select(wrapper, null, {
               multiple: true,
               selected: undefined
            });

            // 选择操作按钮
            let operations = Dom.append(wrapper, 'ul', 'static-schedule-operations',
               `<li data-index="0">&gt;</li>
               <li data-index="1">&lt;</li>
               <li data-index="2">&gt;&gt;</li>
               <li data-index="3">&lt;&lt;</li>
               `
            )

            Dom.addEvent(operations, 'click', e => {
               if (e.target.tagName === 'LI') {
                  this.doStaticScheduleSelected(e.target.getAttribute('data-index'));
               }
            });
            // 已选的浇次
            this.staticScheduleSelectedCastsEl = new Select(wrapper, null, {
               multiple: true,
               selected: undefined
            });
         }, isOk => {
            if(isOk) {
               if(!this.staticScheduleSelectedCastsEl.list || this.staticScheduleSelectedCastsEl.list.length === 0) {
                  alert('请选择需要调度的浇次！');
                  return false;
               }
               let startTime = Utils.dateFill(this.staticScheduleStartTime.value),
                  postData = {
                     startTime: startTime,
                     casts: this.staticScheduleSelectedCastsEl.list.map(cast => {
                        return cast.value
                     })
                  };
                  this.staticScheduleCallback(postData);
            }
            this.staticScheduleModal.hide();
         }, {
               className: 'modal-large'
            });
      } else {
         this.staticScheduleModal.show();
      }

      // 更新状态
      this.staticScheduleStartTime.value = Utils.dateFormat(null, '-', true).replace(' ', 'T');

      let options = '';
      this.staticScheduleFacilities.forEach((f, index) => {
         if (f.facilityType === 'B') {
            options += `<option value="${index}">${f.facilityDesc}</option>`;
         }
      });
      this.staticScheduleFacilityDom.innerHTML = options;
      this.updateStaticScheduleSelect();
   }

   doStaticScheduleSelected(index) {
      let needRenderSelect = false,
         facility = null,
         resetFacility = false;
      switch (index) {
         case "0": //单选
            if (this.staticScheduleCastsEl.value && this.staticScheduleCastsEl.value.length) {
               console.log(this.staticScheduleCastsEl.value)
               // needRenderSelect = true;
               this.staticScheduleCasts.forEach(cast => {
                  if (this.staticScheduleCastsEl.value.indexOf(cast.sid) !== -1) {
                     cast.selected = true;
                     facility = this.staticScheduleFacilities[this.staticScheduleFacilityDom.value];
                     // 选中的数据包含设备信息
                     this.staticScheduleSelectedCasts.push({
                        sid: cast.sid,
                        castNo: cast.castNo,
                        facility: [facility.sid, facility.facilityDesc]
                     });
                  }
               });
               this.staticScheduleCasts = this.staticScheduleCasts.filter(cast => {
                  return !cast.selected
               });
               needRenderSelect = true;
            }
            break;
         case "1": // 取消单选
            if (this.staticScheduleSelectedCastsEl.value && this.staticScheduleSelectedCastsEl.value.length) {
               console.log(this.staticScheduleSelectedCastsEl.value);
               let unSelectCastSid = this.staticScheduleSelectedCastsEl.value.map(value => {
                  return value[0];
               });

               this.staticScheduleSelectedCasts.forEach(cast => {
                  if (unSelectCastSid.indexOf(cast.sid) !== -1) {
                     cast.unselect = true;
                     // 取消选中则没有设备信息
                     this.staticScheduleCasts.push({
                        sid: cast.sid,
                        castNo: cast.castNo
                     });
                  }
               });

               this.staticScheduleSelectedCasts = this.staticScheduleSelectedCasts.filter(cast => {
                  return !cast.unselect;
               });
               needRenderSelect = true;
            }
            break;
         case "2": // 全选
            if (this.staticScheduleCasts.length) {
               facility = this.staticScheduleFacilities[this.staticScheduleFacilityDom.value];
               this.staticScheduleCasts.forEach(cast => {
                  this.staticScheduleSelectedCasts.push({
                     sid: cast.sid,
                     castNo: cast.castNo,
                     facility: [facility.sid, facility.facilityDesc]
                  })
               })
               this.staticScheduleCasts = [];
               needRenderSelect = true;
               resetFacility = true; // 全选需要重置设备信息
            }
            break;
         case "3": // 取消全选
            if (this.staticScheduleSelectedCasts.length) {
               this.staticScheduleSelectedCasts.forEach(cast => {
                  this.staticScheduleCasts.push({
                     sid: cast.sid,
                     castNo: cast.castNo
                  })
               })
               this.staticScheduleSelectedCasts = [];
               needRenderSelect = true;
            }
            break;
         default: ; break;
      }
      if (needRenderSelect) {
         this.updateStaticScheduleSelect(resetFacility);
      }
   }

   updateStaticScheduleSelect() {
      let castItem = this.staticScheduleCasts.map(cast => {
         return {
            value: cast.sid,
            name: cast.castNo
         }
      });
      this.staticScheduleCastsEl.render(castItem);


      let selectCastItem = this.staticScheduleSelectedCasts.map(cast => {
         return {
            value: [cast.sid, cast.facility[0]],
            name: cast.facility[1] + ' | ' + cast.castNo
         }
      });
      this.staticScheduleSelectedCastsEl.render(selectCastItem);
   }
}

export default GanttModal;
